<template>
  <div class="users">
    <el-card>
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <Searchmodule :placeholder="placeholder" @seacherKey="seacher"></Searchmodule>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button   type="primary" icon="el-icon-plus" @click="setDelRole(0)">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 信息表 -->
      <el-table :row-style="{height: '10px'}" :cell-style="{padding:'0px'}" :data="usersList" border stripe v-loading="loading">
        <!-- <el-table-column type="index" label="序号" v-if="false"></el-table-column> -->
        <el-table-column prop="realName" label="姓名" align="center" width="200"   :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="userAccount" label="账号" align="center" width="200"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="mobilePhone" label="电话" align="center" width="200"  :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="roleNames" label="角色" align="center"   :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="状态" align="center" width="200"  :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{scope.row.status.name}}</span>
          </template>
        </el-table-column>
        <el-table-column  label="操作" align="center" width="200">
          <template slot-scope="scope">
            <div class="optBtn-box">
              <el-button type="text"     icon="el-icon-setting" :loading="scope.row.isDel" @click="setDelRole(2,scope.row)">删除</el-button>
            </div>
            <!-- <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false"> -->
            <!--<el-button type="primary"    icon="el-icon-edit" @click="setDelRole(1,scope.row)">详情</el-button>-->
            <!-- </el-tooltip> -->
            <!-- <el-button type="danger"  icon="el-icon-delete" @click="setDelRole(2,scope.row)">修改</el-button> -->

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination
        style="text-align: center;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo"
        :page-sizes="[25,50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog :append-to-body="true" :title="btnId==0?'添加用户':'用户详情'" :visible.sync="addDialogVisible" width="40%" @close="dialogClose()">
      <el-form  v-loading="loadDialog" :model="addForm" :rules="addRules" ref="addRuleForm" label-width="80px">
        <el-form-item label="登录账户" prop="userAccount">
          <el-input v-model="addForm.userAccount" placeholder="电话号码"></el-input>
        </el-form-item>
        <el-form-item  label="登录密码" prop="password">
          <el-input v-model="addForm.password" placeholder="登录密码"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addForm.realName" placeholder="真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="addForm.userName" placeholder="用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-cascader  v-model="addForm.roleIds"  placeholder="选择角色" :options="options" :props="props" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age" type="number" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="certNo">
          <el-input v-model="addForm.certNo" placeholder="身份证号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button v-if="btnId==0" type="primary" :loading="isAdd" @click="addRuleForm" >确 定</el-button>
            <el-button v-if="btnId==1" type="primary" :loading="isAdd" @click="setRoleInfo">保存</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import { pageUser, register, updateUser, findByUserId, deleteByUserId, allRoles } from '@/api/user.js'
import { mapState } from 'vuex'
let $this = null
export default {
  name: 'userManagement',
  computed: {
    ...mapState(['authList'])
  },
  data () {
    return {
      placeholder: '姓名',
      queryInfo: {
        pageNo: 1,
        pageSize: 25,
        realName: ''
      },
      total: 2,
      isAdd: false,
      loading: false,
      addDialogVisible: false,
      loadDialog: false,
      addForm: {
        userAccount: '',
        userName: '',
        password: '',
        realName: '',
        roleIds: [],
        age: '',
        certNo: '',
        phone: ''
      },
      addRules: {
        userAccount: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        // password: [
        // { required: true, message: '请输入密码', trigger: 'blur' },
        // { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        // ],
        realName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' }
        ],
        roleIds: [
          { type: 'array', required: true, message: '请选择用户角色', trigger: 'blur,change' }
        ]
      },
      usersList: [],
      // 角色
      props: { multiple: true },
      options: [],
      btnId: 0
    }
  },
  created () {
    $this = this
    $this.getPageUser()
  },
  methods: {
    authFilter (code) {
      let flag = false
      if (this.authList.length) {
        this.authList.forEach(item => {
          if (item.resourceCode == code) {
            flag = true
          }
        })
      }
      return flag
    },
    // 用户列表
    getPageUser () {
      $this.loading = true
      pageUser($this.queryInfo).then(res => {
        $this.loading = false
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.usersList = res.data.data.records
        $this.total = res.data.data.total
      }).catch(err => {
        $this.loading = false
        return $this.$message.error(err.message)
      })
    },
    // 详情
    findByUserId (row) {
      findByUserId(row.id).then(res => {
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        const arr = []
        res.data.data.roles.forEach(item => {
          arr.push([item.id])
        })
        res.data.data.roleIds = arr
        $this.addForm = res.data.data
      }).catch(err => {})
    },
    deleteByUserId (row) {
      $this.$set(row, 'isDel', true)
      deleteByUserId(row.id).then(res => {
        $this.$set(row, 'isDel', false)
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.getPageUser()
        return $this.$message.success('删除成功')
      }).catch(err => {
        $this.$set(user, 'isDel', false)
      })
    },
    // 修改，删除
    setDelRole (btnId, row) {
      $this.btnId = btnId
      if (btnId == 0 || btnId == 1) {
        $this.allRoles()
        $this.addDialogVisible = true
        if (btnId == 1) { $this.findByUserId(row) }
      } else if (btnId == 2) {
        $this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return $this.deleteByUserId(row)
        }).catch(err => {
          return $this.$message.info('已取消')
        })
      } else {
        return $this.$message.error('操作错误')
      }
    },
    // 修改每页数据条数
    handleSizeChange (val) {
      $this.queryInfo.pageSize = val
      $this.getPageUser()
    },
    // 监听页码值改变
    handleCurrentChange (val) {
      $this.queryInfo.pageNo = val
      $this.getPageUser()
    },
    seacher (key) {
      $this.queryInfo.realName = key
      $this.getPageUser()
    },
    addRuleForm () {
      $this.$refs.addRuleForm.validate((valid) => {
        if (!valid) {
          return $this.$message.error('请完善表单信息')
        }
        $this.isAdd = true
        const newData = Object.assign({}, $this.addForm)
        const arr = []
        newData.roleIds.forEach(item => {
          arr.push(...item)
        })
        newData.roleIds = arr
        register(newData).then(res => {
          $this.isAdd = false
          if (res.data.code != 200) {
            return $this.$message.error(res.data.message)
          }
          $this.addDialogVisible = false
          $this.getPageUser()
        }).catch(err => {
          $this.isAdd = false
          $this.addDialogVisible = false
        })
      })
    },
    setRoleInfo () {
      $this.$refs.addRuleForm.validate((valid) => {
        if (!valid) {
          return $this.$message.error('请完善表单信息')
        }
        $this.isAdd = true
        const newData = Object.assign({}, $this.addForm)
        const arr = []
        newData.roleIds.forEach(item => {
          arr.push(...item)
        })
        newData.roleIds = arr
        updateUser(newData).then(res => {
          $this.isAdd = false
          if (res.data.code != 200) {
            return $this.$message.error(res.data.message)
          }
          $this.addDialogVisible = false
          $this.getPageUser()
        }).catch(err => {
          $this.isAdd = false
          $this.addDialogVisible = false
        })
      })
    },
    dialogClose () {
      $this.addForm = {}
    },
    // 所有角色
    allRoles () {
      $this.loadDialog = true
      allRoles().then(res => {
        $this.loadDialog = false
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.options = res.data.data.map(item => {
          return { value: item.id, label: item.roleName }
        })
      }).catch(err => { $this.loadDialog = false })
    }
  }
}
</script>
<style scoped lang="scss">
  .el-input,.el-cascader{
    width: 70%;
  }

</style>
